package com.xinyue.cross.server.server.handler;

import com.xinyue.cross.server.server.CrossClientChannelCacheManager;
import com.xinyue.cross.server.server.ServerResponseService;
import com.xinyue.game.message.GameServerMessageModel;
import com.xinyue.game.message.GameServerRequestHeader;
import com.xinyue.game.message.GameServerResponseHeader;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NettyHeartbeatHandler extends ChannelInboundHandlerAdapter {
    private static Logger logger = LoggerFactory.getLogger(NettyHeartbeatHandler.class);
    private static final String MESSAGE_URI = "clientHeartbeat";


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        GameServerMessageModel<GameServerRequestHeader> gameServerMessageModel = (GameServerMessageModel) msg;
        GameServerRequestHeader header = gameServerMessageModel.getHeader();
        if (header.getRequestUri().equals(MESSAGE_URI)) {
            logger.debug("收到服务客户端的心跳,header: {}", header);
            CrossClientChannelCacheManager.addCache(header.getClientInstanceId(), ctx);
            GameServerMessageModel<GameServerResponseHeader> responseModel = ServerResponseService.createResponseModel(header);
            ctx.write(responseModel);
        } else {
            ctx.fireChannelRead(gameServerMessageModel);
        }
    }
}
